package dashboard.utils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import org.apache.commons.lang.ObjectUtils;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import dashboard.cache.BeanCache;

public class ReflectUtil {

	/**
	 * 根据属性名获取值,会缓存类信息，在大量反射的情况下,性能会显著提高
	 * @param vo
	 * @param column
	 * @return
	 */
	public static <T>  Object getVal(T vo, String column) {
		try {
			if (vo == null) {
				return null;
			}
//			Field field= Common.getFieldByName(clas, column); curVal =  FieldUtils.readField(field,vo,true);
			Method getM = BeanCache.getGetterMethod(vo.getClass(), column);
			if(!getM.isAccessible()){
				getM.setAccessible(true);	//快速访问，不进行安全检查,在大量反射的情况下,可以提升性能20倍以上
			}
			Object curVal = getM.invoke(vo); //比field.get(vo)效率高

			return curVal;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 按某个字段值分组
	 * @param <T>
	 * @param list
	 * @param fieldName
	 * @return
	 */
	public static <T> TreeMap<String, List<T>> groupByField(List<T> list,String fieldName) {
		TreeMap<String, List<T>> map = Maps.newTreeMap();
		for (T vo : list) {
			String date = (String) getVal(vo, fieldName);
			if (!map.containsKey(date)) {
				map.put(date, new ArrayList<T>());
			}
			map.get(date).add(vo);
		}
		return map;
	}
	
	/**
	 * 按某个字段值分组
	 * @param <T>
	 * @param list
	 * @param fieldName
	 * @return
	 */
	public static <T> TreeMap<String, List<T>> groupByFields(List<T> list,String ...fieldNames) {
		TreeMap<String, List<T>> map = Maps.newTreeMap();
		for (T vo : list) {
			List<String> filedValueList = Lists.newArrayList();
			for(String fieldName: fieldNames){
				String val = (String) getVal(vo, fieldName);
				filedValueList.add(val);
			}
			String key = Joiner.on(">>").join(filedValueList);
			if (!map.containsKey(key)) {
				map.put(key, Lists.<T>newArrayList());
			}
			map.get(key).add(vo);
		}
		return map;
	}
	
	/**
	 * 获取list中某个字段值等于value的VO
	 * @param <T>
	 * @param clas
	 * @param list
	 * @param column
	 * @param value
	 * @return
	 */
	public static <T>  T getByColVal(Class<T> clas, List<T> list,String column,Object value) {
		try {
			if (list == null || list.isEmpty()) {
				return clas.newInstance();
			}
			for (T vo : list) {
				Object curVal =  getVal(vo, column);
				if (ObjectUtils.equals(curVal, value)) {
					return vo;
				}
			}
			return clas.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
